/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package babydisco.GUI;

import babydisco.ECGData;
import babydisco.util.DataReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.File;
import java.util.ArrayList;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.title.*;
import org.jfree.data.category.*;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;

import org.jfree.chart.renderer.xy.*;
import org.jfree.data.xy.*;

/**
 *
 * @author frans
 */
public class GUI extends JFrame
{

    private JTextField textField;
    private String something;
    private JTextArea output;
    private JScrollPane scrollPane;
    private static final String FOURIER = "Fourier Transform";
    private static final String WAVELET = "Wavelet Transform";
    JFileChooser fc;
    private XYDataset left;
    private XYDataset right;
    private ECGData theFinalData;
    
    private ChartPanel leftPanel;
    private ChartPanel rightPanel;
    private JFreeChart chartLeft;
    private JFreeChart chartRight;

    public GUI(String bla)
    {
        super(bla);

        left = createXYDataset();
        right = createXYDataset();

        fc = new JFileChooser();
    }

    /**
     * Creates the gui (needs to be called once this Frame is made)
     * And simply add a new Menu and a new contentPane
     */
    public void createGUI()
    {
        GUI.setDefaultLookAndFeelDecorated(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE); // Anders blijft het programma op de achtergrond lopen tot je ctrl-alt-delete typt
        this.setJMenuBar(this.createMenuBar());
        this.setContentPane(this.createContentPane());

    }

    /**
     * Creates the main contentPane
     */
    private Container createContentPane()
    {
        //Create the content-pane-to-be.
        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.setOpaque(true);

        //Create a scrolled text area.
        output = new JTextArea(6, 5);
        output.setEditable(false);
        scrollPane = new JScrollPane(output);

        JButton loadButton = new JButton("Load Data");
        loadButton.addActionListener(new DataLoadButton());
        JButton button = new JButton("Fourier Transform");
        JButton button2 = new JButton("Wavelet Transform");

        JPanel buttons = new JPanel(new GridLayout(0, 1));
        buttons.add(loadButton);
        buttons.add(button);
        buttons.add(button2);

        JPanel lowerPart = new JPanel(new BorderLayout());
        lowerPart.add(scrollPane, BorderLayout.CENTER);
        lowerPart.add(buttons, BorderLayout.EAST);

        //TODO dit gaat flippen zonder DATA!

        chartLeft = createECGChart(left);
        chartRight = createECGChart(right);

        //JFreeChart chartRight = createTransformChart(createDataset(), GUI.FOURIER);

        leftPanel = new ChartPanel(chartLeft);
        leftPanel.setPreferredSize(new java.awt.Dimension(500, 400));
        rightPanel = new ChartPanel(chartRight);
        rightPanel.setPreferredSize(new java.awt.Dimension(500, 400));

        JPanel leftPane = leftPanel;
        JPanel rightPane = rightPanel;

        JPanel viewPane = new JPanel(new BorderLayout());
        viewPane.add(leftPane, BorderLayout.WEST);
        viewPane.add(rightPane, BorderLayout.EAST);

        lowerPart.setBorder(BorderFactory.createLineBorder(Color.black));

        //Add the text area to the content pane.
        contentPane.add(lowerPart, BorderLayout.SOUTH);
        contentPane.add(viewPane, BorderLayout.NORTH);

        return contentPane;
    }

    /**
     * Creates a sample dataset.
     *
     * @return The dataset.
     */
    private static CategoryDataset createDataset()
    {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(212, "Classes", "JDK 1.0");
        dataset.addValue(504, "Classes", "JDK 1.1");
        dataset.addValue(1520, "Classes", "SDK 1.2");
        dataset.addValue(1842, "Classes", "SDK 1.3");
        dataset.addValue(2991, "Classes", "SDK 1.4");
        return dataset;
    }

    private static XYDataset createXYDataset()
    {
        XYSeries series1 = new XYSeries("First");
        series1.add(1.0, 0.0);
        series1.add(2.0, 0.0);
        series1.add(3.0, 0.0);
        series1.add(4.0, 0.0);
        series1.add(5.0, 0.0);
        series1.add(6.0, 0.0);
        series1.add(7.0, 0.0);
        series1.add(8.0, 0.0);
        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series1);
        return dataset;
    }

    /**
     * Creates a sample chart.
     *
     * @param dataset a dataset.
     *
     * @return The chart.
     */
    private static JFreeChart createECGChart(XYDataset dataset)
    {
// create the chart...
        JFreeChart chart = ChartFactory.createXYLineChart(
                "ECG View",
                // chart title
                "time",
                // domain axis label
                "voltage",
                // range axis label
                dataset,
                // data
                PlotOrientation.VERTICAL,
                // orientation
                false,
                // include legend
                true,
                // tooltips
                false // urls
                );
        //chart.addSubtitle(new TextTitle("Number of Classes By Release"));

        /*TextTitle source = new TextTitle(
        "Source: Java In A Nutshell (4th Edition) "
        + "by David Flanagan (O’Reilly)");
        source.setFont(new Font("SansSerif", Font.PLAIN, 10));
        source.setPosition(RectangleEdge.BOTTOM);
        source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        chart.addSubtitle(source);  */

        chart.setBackgroundPaint(Color.white);
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.white);
        plot.setDomainGridlinePaint(Color.white);

// customise the range axis...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

// customise the renderer...
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
        renderer.setShapesVisible(true);
        renderer.setShapesFilled(true);

        return chart;
    }

    private static JFreeChart createTransformChart(CategoryDataset dataset, String type)
    {
// create the chart...
        JFreeChart chart = ChartFactory.createLineChart(
                type + " View",
                // chart title
                "frequency",
                // domain axis label
                "amplitude",
                // range axis label
                dataset,
                // data
                PlotOrientation.VERTICAL,
                // orientation
                false,
                // include legend
                true,
                // tooltips
                false // urls
                );
        //chart.addSubtitle(new TextTitle("Number of Classes By Release"));

        /*TextTitle source = new TextTitle(
        "Source: Java In A Nutshell (4th Edition) "
        + "by David Flanagan (O’Reilly)");
        source.setFont(new Font("SansSerif", Font.PLAIN, 10));
        source.setPosition(RectangleEdge.BOTTOM);
        source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        chart.addSubtitle(source);  */
        chart.setBackgroundPaint(Color.white);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.white);
// customise the range axis...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// customise the renderer...
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setShapesVisible(true);
        renderer.setDrawOutlines(true);
        renderer.setUseFillPaint(true);
        renderer.setFillPaint(Color.white);
        return chart;
    }

    /**
     * Creates the menuBar
     * @return 
     */
    private JMenuBar createMenuBar()
    {
        JMenuBar menuBar;
        JMenu menu;
        JMenuItem saveMenuItem, quitMenuItem, openMenuItem, loadDataMenuItem;
        //Create the menu bar.
        menuBar = new JMenuBar();

        //Build the first menu.
        menu = new JMenu("File");

        menu.getAccessibleContext().setAccessibleDescription("Main menu");

        saveMenuItem = new JMenuItem("Save");
        saveMenuItem.addActionListener(new SaveButton());
        quitMenuItem = new JMenuItem("Exit");
        quitMenuItem.addActionListener(new QuitButton());
        openMenuItem = new JMenuItem("Open");
        openMenuItem.addActionListener(new OpenButton());
        loadDataMenuItem = new JMenuItem("Load Data");
        loadDataMenuItem.addActionListener(new DataLoadButton());

        menu.add(loadDataMenuItem);
        menu.add(openMenuItem);
        menu.add(saveMenuItem);
        menu.addSeparator();
        menu.add(quitMenuItem);

        menuBar.add(menu);

        //Build second menu in the menu bar.
        menu = new JMenu("Help");
        menu.getAccessibleContext().setAccessibleDescription("Might contain help files in the future");
        menuBar.add(menu);



        return menuBar;
    }
    
    public ECGData getECGData()
    {
        return theFinalData;
    }

    private class SaveButton implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO: add saving logic
            something = "Save logic here!\n";
            output.append(something);
        }
    }

    private class OpenButton implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO: add opening logic
            something = "Open logic here!\n";
            output.append(something);
        }
    }

    private class DataLoadButton implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            int returnVal = fc.showOpenDialog(GUI.this);
            if (returnVal == JFileChooser.APPROVE_OPTION)
            {
                File file = fc.getSelectedFile();
                String data = file.getAbsolutePath();
                System.out.println("trying to open something");
                try
                {
                    ArrayList[] newData = DataReader.read(data);
                    System.out.println("DataReader stuff done");
                    double[] sampleSampleFrequency = {(1 / 0.001),(1 / 0.001),(1 / 0.001),(1 / 0.001),(1 / 0.001),( 1/  0.001),(1 / 0.001)};
                    theFinalData = new ECGData(newData, sampleSampleFrequency);
                    System.out.println("ECG data made (fourier aswell)");
                    left = theFinalData.createNormalDataset("data", 1);
                    right = theFinalData.createFourierDataset("data", 1);
                    System.out.println("JCharts made");
                    
                    chartLeft = createECGChart(left);
                    chartRight = createECGChart(right);
                    leftPanel.repaint();
                    rightPanel.repaint();
                    repaint(); // Should repaint the everything including the 2 graphs!
                    
                    /**
                     * Tijdelijke code! TODO: WEGHALEN EN REFRESH/REPAINT FIXEN!
                     */
                    JFrame frame = new JFrame("Temp solution");
                    frame.setSize(1024,555);
                    
                    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    
                    leftPanel = new ChartPanel(chartLeft);
                    leftPanel.setPreferredSize(new java.awt.Dimension(500, 400));
                    rightPanel = new ChartPanel(chartRight);
                    rightPanel.setPreferredSize(new java.awt.Dimension(500, 400));

                    JPanel leftPane = leftPanel;
                    JPanel rightPane = rightPanel;
                    JPanel viewPane = new JPanel(new BorderLayout());
                    viewPane.add(leftPane, BorderLayout.WEST);
                    viewPane.add(rightPane, BorderLayout.EAST);
                    
                    frame.setContentPane(viewPane);
                    frame.setVisible(true);
                }
                catch (IOException ex)
                {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                something = "Opening: " + file.getName() + ".\n";
            }
            else
            {
                something = "Open command cancelled by user. \n";
            }
            output.append(something);
        }
    }

    private class QuitButton implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO: add saving logic
            setVisible(false);
            dispose();
            System.exit(0);
        }
    }
}
